﻿@inject IHttpService _httpService
@inject IPopupService PopupService


@if (Model == null)
{
    <CnGalWebSite.Components.Progressings.ProgressingCard />
}
else
{
    <MCard>
        <MCardTitle>
            @(Id==0? "添加应用" : "编辑应用")  @Model.ClientName
        </MCardTitle>
        <MCardText>
            Id：@Model.Id
        </MCardText>
        <MCardText>
            <MRow>
                <MCol Cols="12" Md="6">
                    <MTextField @bind-Value="Model.ClientName" Label="应用名称" HideDetails="true" />

                </MCol>
                <MCol Cols="12" Md="6">
                    <MTextField @bind-Value="Model.ClientUri" Label="应用主页" HideDetails="true" />
                </MCol>

                <MCol Cols="12">
                    <MTextarea Rows="3" @bind-Value="Model.Description" Label="应用简介" HideDetails="true" />
                </MCol>
                <MCol Cols="12">
                    @if (!string.IsNullOrWhiteSpace(Model.LogoUri))
                    {
                        <MImage Height="50" Width="50" Src="@Model.LogoUri" />
                    }
                    <MTextField @bind-Value="Model.LogoUri" Label="LOGO（请使用CnGal图床上传正方形图片）" HideDetails="true" />
                </MCol>
                <MCol Cols="12" Lg="6" Xl="4">
                    <MCheckbox @bind-Value="Model.Enabled" Label="启用" TValue="bool" HideDetails="true" />

                </MCol>
                <AuthorizeView Roles="Admin">
                    <MCol Cols="12" Lg="6" Xl="4">
                        <MCheckbox @bind-Value="Model.RequireConsent" Label="展示用户同意页面" TValue="bool" HideDetails="true" />
                    </MCol>
                    <MCol Cols="12" Lg="6" Xl="4">
                        <MCheckbox @bind-Value="Model.RequireClientSecret" Label="需要验证客户端密钥" TValue="bool" HideDetails="true" />
                    </MCol>
                    <MCol Cols="12" Lg="6" Xl="4">
                        <MCheckbox @bind-Value="Model.RequirePkce" Label="必须发送证明密钥（PKCE）" TValue="bool" HideDetails="true" />
                    </MCol>
                    <MCol Cols="12" Lg="6" Xl="4">
                        <MCheckbox @bind-Value="Model.AllowAccessTokensViaBrowser" Label="允许客户端通过浏览器接收访问令牌" TValue="bool" HideDetails="true" />
                    </MCol>
                </AuthorizeView>
                <MCol Cols="12">
                    <InputCheckboxList Title="使用的授权方式" Items="Model.AllowedGrantTypes" AllItems="_allowedGrantTypes" />
                </MCol>
                <MCol Cols="12">
                    <InputCheckboxList Title="权限（请慎重选择所需权限，过高的权限用户可能拒绝授权）" Items="Model.AllowedScopes" AllItems="AllowedScopes" />
                </MCol>
                <MCol Cols="12">
                    <SecretCard Id="Model.Id" ClientId="@Model.ClientId" />
                </MCol>

                <MCol Cols="12" Md="6">
                    <InputStringListCard Title="主域" SubTitle="网站运行时的根Url" Items="Model.AllowedCorsOrigins" />
                </MCol>
                <MCol Cols="12" Md="6">
                    <InputStringListCard Title="登入回调地址" SubTitle="登录成功之后将要跳转的Url" Items="Model.RedirectUris" />
                </MCol>
                <MCol Cols="12" Md="6">
                    <InputStringListCard Title="登出回调地址" SubTitle="登出之后将要跳转的Url" Items="Model.PostLogoutRedirectUris" />
                </MCol>
            </MRow>

        </MCardText>
        <MCardActions Class="pb-6">
            <MSpacer></MSpacer>
            <MButton Color="primary"
                     Text
                     OnClick="SaveEdit">
                <MIcon Left>mdi-check</MIcon>
                保存
            </MButton>
        </MCardActions>

    </MCard>

}



@code {
    [Parameter]
    public int Id { get; set; }
    [Parameter]
    public EventCallback<ClientEditModel> OnEdited { get; set; }

    [Parameter]
    public IEnumerable<KeyValuePair<string, string>> AllowedScopes { get; set; }

    ClientEditModel Model;

    private string _baseUrl = "api/clients/";
    private string _name = "客户端";


    [CascadingParameter]
    public ErrorHandler ErrorHandler { get; set; }




    IEnumerable<KeyValuePair<string, string>> _allowedGrantTypes = new List<KeyValuePair<string, string>>
{
        new KeyValuePair<string, string>("authorization_code","授权码"),
        new KeyValuePair<string, string>("password","密码")
    };
    IEnumerable<KeyValuePair<string, string>> _allowedScopes = new List<KeyValuePair<string, string>>
{
        new KeyValuePair<string, string>("openid","查看OpenID"),
        new KeyValuePair<string, string>("profile","查看用户资料"),
        new KeyValuePair<string, string>("IdentityServerApi","管理开放平台"),
        new KeyValuePair<string, string>("role","查看用户角色"),
    };

    protected override async Task OnInitializedAsync()
    {
        await Refresh();
    }

    public async Task Refresh()
    {
        try
        {
            Model = null;
            StateHasChanged();
            Model = Id == 0 ? new ClientEditModel() : await _httpService.GetAsync<ClientEditModel>($"{_baseUrl}edit?id={Id}");
            StateHasChanged();
        }
        catch (Exception ex)
        {
            await ErrorHandler.ProcessError(ex, $"获取{_name}信息失败");
        }
    }

    public async Task SaveEdit()
    {
        try
        {
            var result = await _httpService.PostAsync<ClientEditModel, Result>($"{_baseUrl}edit", Model);
            if (result.Success)
            {
                if (!string.IsNullOrWhiteSpace(result.Message))
                {
                    await PopupService.ToastAsync(result.Message, AlertTypes.Success);
                }
                await OnEdited.InvokeAsync(Model);
                StateHasChanged();
            }
            else
            {
                await PopupService.ToastAsync(result.Message ?? "操作失败", AlertTypes.Error);
            }
        }
        catch (Exception ex)
        {
            await ErrorHandler.ProcessError(ex, Model.Id == 0 ? $"添加{_name}失败" : $"编辑{_name}信息失败");
        }

    }
}
